import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { 
  getAIVideoConfig, 
  saveAIVideoConfig, 
  isVideoTokenConfigured, 
  validateVideoToken, 
  getAvailableVideoProviders, 
  getVideoProviderModels,
  getFreeVideoProviders
} from '../services/aiVideoConfigService';
import './AIVideoConfig.css';

const AIVideoConfig = ({ onClose, onConfigSaved }) => {
  const { t } = useTranslation();
  const [config, setConfig] = useState(getAIVideoConfig());
  const [showToken, setShowToken] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [errors, setErrors] = useState({});
  const [providers] = useState(getAvailableVideoProviders());
  const [freeProviders] = useState(getFreeVideoProviders());
  const [models, setModels] = useState(getVideoProviderModels(config.provider));
  const [showFreeOnly, setShowFreeOnly] = useState(false);

  useEffect(() => {
    setModels(getVideoProviderModels(config.provider));
  }, [config.provider]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setConfig(prev => ({ ...prev, [name]: value }));
    
    // Clear error for this field
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const handleProviderChange = (e) => {
    const provider = e.target.value;
    const providerConfig = providers.find(p => p.id === provider);
    setConfig(prev => ({
      ...prev,
      provider,
      endpoint: providerConfig.endpoint,
      model: getVideoProviderModels(provider)[0]?.id || '',
      isFree: providerConfig.isFree
    }));
    
    // Clear error for this field
    if (errors.provider) {
      setErrors(prev => ({ ...prev, provider: '' }));
    }
  };

  const validateForm = () => {
    const newErrors = {};
    
    if (!config.apiToken) {
      newErrors.apiToken = t('aiVideoConfig.tokenRequired');
    } else if (!validateVideoToken(config.apiToken)) {
      newErrors.apiToken = t('aiVideoConfig.tokenInvalid');
    }
    
    if (!config.provider) {
      newErrors.provider = t('aiVideoConfig.providerRequired');
    }
    
    if (!config.model) {
      newErrors.model = t('aiVideoConfig.modelRequired');
    }
    
    if (!config.endpoint) {
      newErrors.endpoint = t('aiVideoConfig.endpointRequired');
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSave = async () => {
    if (!validateForm()) {
      return;
    }
    
    setIsSaving(true);
    try {
      const success = saveAIVideoConfig(config);
      if (success) {
        onConfigSaved && onConfigSaved();
        onClose && onClose();
      } else {
        setErrors({ general: t('aiVideoConfig.saveError') });
      }
    } catch (error) {
      console.error('Error saving AI Video config:', error);
      setErrors({ general: t('aiVideoConfig.saveError') });
    } finally {
      setIsSaving(false);
    }
  };

  const handleReset = () => {
    if (window.confirm(t('aiVideoConfig.resetConfirm'))) {
      setConfig(getAIVideoConfig());
      setErrors({});
    }
  };

  const toggleTokenVisibility = () => {
    setShowToken(!showToken);
  };

  const toggleFreeProviders = () => {
    setShowFreeOnly(!showFreeOnly);
  };

  const filteredProviders = showFreeOnly ? freeProviders : providers;

  return (
    <div className="ai-video-config-overlay">
      <div className="ai-video-config-modal">
        <div className="ai-video-config-header">
          <h2>{t('aiVideoConfig.title')}</h2>
          <button className="close-btn" onClick={onClose} aria-label="Close">
            ×
          </button>
        </div>
        
        <div className="ai-video-config-content">
          {errors.general && (
            <div className="error-message">{errors.general}</div>
          )}
          
          <div className="config-form">
            <div className="free-filter">
              <label className="checkbox-label">
                <input
                  type="checkbox"
                  checked={showFreeOnly}
                  onChange={toggleFreeProviders}
                />
                <span className="checkmark"></span>
                {t('aiVideoConfig.showFreeOnly')}
              </label>
              <span className="free-count">
                ({freeProviders.length} {t('aiVideoConfig.freeProviders')})
              </span>
            </div>
            
            <div className="form-group">
              <label htmlFor="provider">{t('aiVideoConfig.provider')}</label>
              <select
                id="provider"
                name="provider"
                value={config.provider}
                onChange={handleProviderChange}
                className={errors.provider ? 'error' : ''}
              >
                {filteredProviders.map(provider => (
                  <option key={provider.id} value={provider.id}>
                    {provider.name} {provider.isFree ? `(${t('aiVideoConfig.free')})` : ''}
                  </option>
                ))}
              </select>
              {errors.provider && (
                <div className="field-error">{errors.provider}</div>
              )}
              {config.provider && (
                <div className="provider-info">
                  <p>{providers.find(p => p.id === config.provider)?.description}</p>
                  <a 
                    href={providers.find(p => p.id === config.provider)?.website} 
                    target="_blank" 
                    rel="noopener noreferrer"
                    className="provider-link"
                  >
                    {t('aiVideoConfig.visitWebsite')}
                  </a>
                </div>
              )}
            </div>
            
            <div className="form-group">
              <label htmlFor="model">{t('aiVideoConfig.model')}</label>
              <select
                id="model"
                name="model"
                value={config.model}
                onChange={handleChange}
                className={errors.model ? 'error' : ''}
              >
                {models.map(model => (
                  <option key={model.id} value={model.id}>
                    {model.name}
                  </option>
                ))}
              </select>
              {errors.model && (
                <div className="field-error">{errors.model}</div>
              )}
              {config.model && (
                <div className="model-info">
                  <p>{models.find(m => m.id === config.model)?.description}</p>
                </div>
              )}
            </div>
            
            <div className="form-group">
              <label htmlFor="apiToken">{t('aiVideoConfig.apiToken')}</label>
              <div className="token-input-group">
                <input
                  id="apiToken"
                  name="apiToken"
                  type={showToken ? 'text' : 'password'}
                  value={config.apiToken}
                  onChange={handleChange}
                  placeholder={t('aiVideoConfig.tokenPlaceholder')}
                  className={errors.apiToken ? 'error' : ''}
                />
                <button
                  type="button"
                  className="token-visibility-btn"
                  onClick={toggleTokenVisibility}
                  aria-label={showToken ? 'Hide token' : 'Show token'}
                >
                  {showToken ? '👁️' : '👁️‍🗨️'}
                </button>
              </div>
              {errors.apiToken && (
                <div className="field-error">{errors.apiToken}</div>
              )}
              <div className="field-help">
                {providers.find(p => p.id === config.provider)?.tokenHelp || t('aiVideoConfig.tokenHelp')}
              </div>
            </div>
            
            <div className="form-group">
              <label htmlFor="endpoint">{t('aiVideoConfig.endpoint')}</label>
              <input
                id="endpoint"
                name="endpoint"
                type="text"
                value={config.endpoint}
                onChange={handleChange}
                className={errors.endpoint ? 'error' : ''}
                readOnly={true}
              />
              {errors.endpoint && (
                <div className="field-error">{errors.endpoint}</div>
              )}
              <div className="field-help">
                {t('aiVideoConfig.endpointHelp')}
              </div>
            </div>
            
            <div className="form-group">
              <label htmlFor="maxTokens">{t('aiVideoConfig.maxTokens')}</label>
              <input
                id="maxTokens"
                name="maxTokens"
                type="number"
                min="100"
                max="8000"
                value={config.maxTokens}
                onChange={handleChange}
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="temperature">
                {t('aiVideoConfig.temperature')}: {config.temperature}
              </label>
              <input
                id="temperature"
                name="temperature"
                type="range"
                min="0"
                max="2"
                step="0.1"
                value={config.temperature}
                onChange={handleChange}
              />
            </div>
          </div>
        </div>
        
        <div className="ai-video-config-footer">
          <button
            type="button"
            className="secondary-btn"
            onClick={handleReset}
            disabled={isSaving}
          >
            {t('aiVideoConfig.reset')}
          </button>
          <div className="footer-spacer"></div>
          <button
            type="button"
            className="secondary-btn"
            onClick={onClose}
            disabled={isSaving}
          >
            {t('aiVideoConfig.cancel')}
          </button>
          <button
            type="button"
            className="primary-btn"
            onClick={handleSave}
            disabled={isSaving}
          >
            {isSaving ? t('aiVideoConfig.saving') : t('aiVideoConfig.save')}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AIVideoConfig;